package com.itheima.reggie.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    @Cacheable(value = "dish",key = "#dishDto.categoryId + '_' + #dishDto.status")
    public R save(@RequestBody DishDto dishDto) {

        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);
        //清理所有菜品的缓存数据
        /*Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/
        //清理某个分类下面的菜品缓存数据
        /*String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);*/
        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R pageQuery(Integer page, Integer pageSize, String name) {
        log.info("page = {},pagesize = {},name = {}", page, pageSize, name);
        //参数封装
        Page<Dish> pageInfo = new Page(page, pageSize);
        Page<DishDto> disDtoPage = new Page<>();
        //封装查询条件
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name), Dish::getName, name);

        qw.orderByDesc(Dish::getUpdateTime);//降序
        //开始查询
        dishService.page(pageInfo, qw);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo, disDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();//总记录数
        //重新封装集合
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            //根据id查询菜品分类
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());//重新封装集合
        disDtoPage.setRecords(list);

        return R.success(disDtoPage);
    }

    @GetMapping("/{id}")
    public R get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }


    @DeleteMapping
    @CacheEvict(value = "dish",allEntries = true)
    public R deleteDish(@RequestParam List<Long> ids) {
        System.out.println(ids);
        dishService.deleteWithFlavor(ids);
        return R.success("删除成功");
    }

    @PostMapping("/status/{status}")
    @CacheEvict(value = "dish",allEntries = true)
    public R updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {

        LambdaUpdateWrapper<Dish> qwdish = new LambdaUpdateWrapper<>();
        qwdish.set(Dish::getStatus, status);
        qwdish.in(Dish::getId, ids);

        dishService.update(qwdish);
      /*  for (Long id : ids) {
            //Dish dish = dishService.getById(id);
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
*/
        return R.success("操作成功");
    }

    @PutMapping
    @CacheEvict(value = "dish",allEntries = true)
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);

        //清理所有菜品的缓存数据
        /*Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/
        /*//清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);*/

        return R.success("修改菜品成功");
    }


    @GetMapping("/list")
    @Cacheable(value = "dish",key = "#categoryId + '_' + #status")
    public R<List<DishDto>> list(Long categoryId, Integer status) {
/*
        List<DishDto> dishDtoList = null;
        //动态构造key
        String key = "dish_" + categoryId + "_" + status;//dish_1397844391040167938_1
        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null) {
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }
*/
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(categoryId != null, Dish::getCategoryId, categoryId);
        //添加条件
        qw.eq(Dish::getStatus, status);
        qw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //添加排序条件
        List<Dish> list = dishService.list(qw);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtil.copyProperties(item, dishDto);

            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //获取caipinid
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> qwFlavor = new LambdaQueryWrapper<>();
            qwFlavor.eq(DishFlavor::getDishId, dishId);
            //根据
            List<DishFlavor> dishFlavorList = dishFlavorService.list(qwFlavor);
            dishDto.setFlavors(dishFlavorList);
            //根据菜品id查询菜品口味
            return dishDto;

        }).collect(Collectors.toList());

        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        //redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
